package com.tanhua.dubbo.server.api;

import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(version = "1.0.0")
public class ManageVideoApiImpl implements ManageVideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public PageInfo<Video> queryVideoListById(Long uid, Integer page, Integer pageSize, String sortProp, String sortOrder) {
        PageRequest pageRequest=null;

        if (StrUtil.isNotEmpty(sortProp) && StrUtil.isNotEmpty(sortOrder)) {
            //设置排序
            sortProp = StrUtil.toUnderlineCase(sortProp);
            Sort sortDesc = Sort.by(Sort.Order.desc(sortProp));
            Sort sortAsc = Sort.by(Sort.Order.asc(sortProp));
            if ("ascending".equals(sortOrder)) {
                pageRequest = PageRequest.of(page - 1, pageSize, sortAsc);
            } else {
                pageRequest = PageRequest.of(page - 1, pageSize, sortDesc);
            }

            Query query = Query.query(Criteria.where("userId").is(uid)).with(pageRequest);
            List<Video> videos = this.mongoTemplate.find(query, Video.class);
            PageInfo<Video> pageInfo = new PageInfo<>();
            pageInfo.setRecords(videos);
            pageInfo.setPageNum(page);
            pageInfo.setPageSize(pageSize);
            pageInfo.setTotal(videos.size());
            return pageInfo;
        }
        return null;
    }
}
